function Group() {
    //this.table=this.InitTable();
    this.comboboxm = this.InitParent();
    this.tab = this.InitTab();
    this.form = this.InitEleUI();
    //this.tree=this.InitTree();
    //$("#tree-content").height($(window).height()-100);
    this.grid = this.InitGrid();

    this.orgidobj = null;
}

Group.prototype.InitParent = function () {
    var width = ($(window).width() - 50) * 0.6 * 0.8 - 90;
    var comboboxm = $("#parentid").ligerComboBox({
        valueField: 'orgid',
        textField: 'orgname',
        selectBoxWidth: width - 2,
        selectBoxHeight: 300,
        treeLeafOnly: false,
        valueFieldID: "hid",
        tree: {
            url: '../common/get_org_list?orgtype=0',
            checkbox: false,
            nodeWidth: width - 100,
            ajaxType: 'get',
            idFieldName: 'orgid',
            textFieldName: "orgname",
            idField: "orgid",
            parentIDField: "orgparentid"
        },
        onSelected: function (orgid, orgname) {// id为空值，name为选择的值
            $("#hidparentid").val(orgid);

        },
        width: width
    });
    return comboboxm;
}


Group.prototype.InitEleUI = function () {
    var form;
    layui.use('form', function () {
        form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
        form.render();
    });
    return form;
}
Group.prototype.InitTab = function () {
    var element;
    var _this = this;
    layui.use('element', function () {
        element = layui.element;
        element.on('tab(tabcontent)', function (data) {
            //alert(data.index);
            if (data.index == 0) {
                _this.comboboxm.setEnabled();
                document.formedit.reset();
                document.formedit.orgid.value = 0;
                _this.form.render();
            }

        })
    });
    return element;
}

Group.prototype.OpTab = function (tabindex, obj) {
    this.tab.tabChange('tabcontent', tabindex);
    //this.orgidobj=obj;
    if (obj) {
        document.formedit.orgname.value = obj.orgname;
        document.formedit.remark.value = obj.remark;
        document.formedit.orgid.value = obj.orgid;
        document.formedit.orderindex.value = obj.orderindex;
        this.comboboxm.selectValue(obj.orgparentid);
        this.comboboxm.setDisabled();
        this.form.render();
        //this.form.render('select');
    }
}

Group.prototype.InitTree = function () {
    $.ajax({
        type: "POST",
        url: "get_list",
        data: {rolename: $("#rolename").val()},
        beforeSend: function (XHR) {
            //{"rowNum":1,"orgid":19,"orgparentid":0,"orgname":"行政组织机构","orgtype":0,"lft":1,"rgt":110,"level":0,"path":null,"createtime":"2018-05-02 17:52:37","remark":"行政组织机构","ischecked":null,
        },
        success: function (data) {
            data = eval('(' + data + ')');

            if (data.code == 0) {
                var treedata = [];
                var data = data.data;
                var treedata = createTreeData(data, 0);
                //console.log(JSON.stringify(dd));

                layui.tree({
                    elem: '#tree' //传入元素选择器
                    , nodes: treedata
                    , skin: 'huang'
                });


            }
        },
        complete: function (XHR) {

        },
        error: function () {

        }
    });
}

Group.prototype.InitTable = function () {
    var table;
    var _this = this;
    layui.use('table', function () {
        table = layui.table;
        table.render({
            elem: '#list'
            , height: $(window).height() - 120
            , url: 'get_list_group' // 数据接口
            , page: true // 开启分页
            , limit: 30
            , id: 'orglist'
            , method: "post"
            , cols: [[ // 表头
                //,{type:'numbers'}
                {field: 'orgname', title: '机构名称', width: 250, align: 'left'}
                , {field: 'orgtype', title: '类型', width: 120, align: 'center'}
                , {field: 'createtime', title: '时间', width: 170, align: 'center'}
                , {field: 'remark', title: '描述', width: 200, align: 'center'}
                , {title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#operate'}
            ]]
            , request: {
                type: 'post'
            }
            , page: false
            , where: {rolename: $("#rolename").val()}
            , done: function (res, page, count) {
                var dataarr = res.data;
                $("[data-field='orgname']").children().each(function (index) {
                    if (index == 0) {
                        $(this).css({"text-align": "center"});
                    }
                    var thisdata = dataarr[index - 1];
                    if (thisdata) {
                        var text = $(this).text();
                        $(this).css({"text-indent": thisdata.level + "em"});
                    }
                })
            }

        });


        //监听工具条
        table.on('tool(list)', function (obj) {
            var data = obj.data;
            if (obj.event === 'detail') {
                layer.msg('ID：' + data.id + ' 的查看操作');
            } else if (obj.event === 'del') {

                top.mylayui.confirm('确定要删除吗？', {icon: 0}, function (index, dd) {
                    top.mylayui.close(index);
                    vGroup.deleteentity(data.orgid);
                });
            } else if (obj.event === 'edit') {
                //layer.alert('编辑行：<br>'+ JSON.stringify(data))
                _this.OpTab(2, data);
            }
        });


    });

    return table;
}

Group.prototype.searchtable = function () {
    this.table.reload('orglist', {
        page: {
            curr: 1 //重新从第 1 页开始
        }, page: false
        , where: {
            rolename: $("#rolename").val()
        }
    });
}

Group.prototype.openadduser = function (groupid, orgparentid) {
    top.mylayui.open({
        type: 2,
        title: '用户添加',
        shadeClose: true,
        shade: 0.5,
        area: ['870px', '550px'],
        content: 'org/group_user?groupid=' + groupid + "&orgparentid=" + orgparentid
    });

    var iframeele = top.$(".layui-layer-content").find('iframe');
    iframeele.css({"height": $(iframeele).height() - 10});
}

Group.prototype.deleteentity = function (orgid) {
    top.mylayui.confirm('确定要删除吗？', {icon: 0}, function (index) {
        top.mylayui.close(index);

        $.ajax({
            type: "POST",
            url: "delete_org",
            data: {orgid: orgid},
            beforeSend: function (XHR) {

            },
            success: function (data) {
                data = eval('(' + data + ')');
                if (data.result > 0) {
                    top.mylayui.msg(data.msg, {icon: 1});
                    //vOrg.searchtable();
                    document.location.reload();
                }
                else {
                    top.mylayui.msg(data.msg, {icon: 0});
                }
            },
            complete: function (XHR) {

            },
            error: function () {

            }
        });
    })
}

Group.prototype.funeditentity = function (orgid, orgname, orgparentid, remark, orderindex) {
    var data = {orgid: orgid, orgname: orgname, orgparentid: orgparentid, remark: remark, orderindex: orderindex};
    vGroup.OpTab(2, data);
}

Group.prototype.InitGrid = function () {
    var _this = this;
    window.liger.remove("list");
    if (_this.grid == null) {
        _this.grid = $("#list").ligerGrid({
            columns: [
                //{ display: '序号', width: 80, name: 'rowNum' },
                {display: '机构名称', width: 250, align: 'left', name: 'orgname', id: "orgname"},
                {
                    display: '创建时间', width: 180, name: 'createtime', render: function (rowdata, rowindex, value) {
                        return value;
                    }
                },
                {display: '描述', width: 200, name: 'remark'},
                {
                    display: '操作', width: 100, name: 'userid', render: function (rowdata, rowindex, value) {
                        if (rowdata.orgtype == 1) {
                            var html = ' <img class="btn-img" style="vertical-align:middle" src="' + ctxStatic + '/images/index/btn_edit.png" onclick="vGroup.funeditentity(' + rowdata.orgid + ',\'' + rowdata.orgname + '\',' + rowdata.orgparentid + ',\'' + rowdata.remark + '\',' + rowdata.orderindex + ')"  alt="编辑" title="编辑">';
                            html += '<img class="btn-img" style="vertical-align:middle" src="' + ctxStatic + '/images/index/btn_delete.png" onclick="vGroup.deleteentity(' + rowdata.orgid + ')"  alt="删除" title="删除">';
                            //html+=' <img class="btn-img" style="vertical-align:middle" src="'+ctxStatic+'/images/button/setuser.png" onclick="vGroup.openadduser('+rowdata.orgid+','+rowdata.orgparentid+')" alt="设置人员" title="设置人员">';
                            return html;
                        }

                    }
                }
            ],
            pageSize: 30,
            url: "get_list_group" + '?time=' + new Date().getTime(),
            delayLoad: false,            //初始化时是否加载,为true时,不加载,为false时,则加载
            sortName: null,
            dataAction: 'server',
            parms: {
                Method: "",
                rolename: $("#rolename").val()
            },
            sortOrder: null,
            sourceObj: _this.grid,
            root: 'items',                       //数据源字段名
            record: 'countRecord',                    //数据源记录数字段名
            pageParmName: 'CurrentPage',               //页索引参数名，(提交给服务器)
            pagesizeParmName: 'PageSize',        //页记录数参数名，(提交给服务器)
            data: {},
            isExpand: true,
            width: "100%",
            height: '100%',
            heightDiff: 0,
            rowHeight: 28,
            onSuccess: function (rowdata, rowindex) {

                if (rowdata.status > 0) {
                    alert(rowdata.msg)
                }


                return;
                for (var i = 0; i < rowdata.items.length; i++) {

                    var rowIndex = 'r' + (10001 + i)
                    $("#list").ligerGrid().collapse(rowIndex)


                }


            },
            alternatingRow: true,
            border: 0,
            usePager: false,
            tree: {
                columnId: "orgname",
                idField: "orgid",
                parentIDField: "orgparentid"

            },onAfterShowData:function () {
                $("#list").ligerGrid().collapseAll();
            }
        })
    }
}


var vGroup;
$(function () {
    vGroup = new Group();
})


function CloseDialog(result, msg) {
    if (result > 0) {
        top.mylayui.msg('操作成功', {icon: 1});
        document.formedit.reset();
        //vOrg.searchtable();
        //vOrg.OpTab(1);
        document.location.reload();
    }
    else {
        if (msg) {
            top.mylayui.msg(msg, {icon: 0});
        } else {
            top.mylayui.msg('操作失败', {icon: 0});
        }
    }
}


/*
 * 传入的数组有id和父节点pid字段，通过它们的关联构造成一棵或多棵树结构
 * @param nodes 集合
 * @param treeRootId 根节点的id
 */
function createTreeData(nodes, treeRootId) {
    var groups = {};
    var treeRootPid = 0;
    // 按父节点将节点分组
    for (var i in nodes) {
        if (!groups[nodes[i].orgparentid]) {
            groups[nodes[i].orgparentid] = [];
        }
        groups[nodes[i].orgparentid].push(nodes[i]);
        if (treeRootPid && treeRootPid === nodes[i].orgid) { // 发现传入的根节点id作为节点id时，将根节点设置为该节点的父节点
            treeRootPid = nodes[i].orgparentid;
        }
    }

    var rootNodes = groups[treeRootPid];
    //rootNodes.name=rootNodes.orgname;
    //rootNodes.id=rootNodes.orgid;
    groups[treeRootPid] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
    function traverseTreeNodeGroup(treeNodeGroup) {
        for (var i in treeNodeGroup) {
            var node = treeNodeGroup[i];
            node.name = node.orgname;
            node.id = node.orgid;
            node.spread = true;
            if (groups[node.orgid]) {
                node.children = groups[node.orgid];
                groups[node.orgid] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
                traverseTreeNodeGroup(node.children);
            }
        }
    }

    traverseTreeNodeGroup(rootNodes);
    return rootNodes;
}